<template>
  <view class="conversations-container">
    <navigation v-if="shop" :shop="shop" title="客服中心"></navigation>
    <scroll-view class="conversations" scroll-y="true" enable-flex="true">
      <view class="scroll-item" v-if="group_id == 2">
        <view class="item-head">
          <image src="/static/images/customer.png" class="head-icon"></image>
          <view v-if="pendingConversationAmount" class="item-head_unread">{{pendingConversationAmount}}
          </view>
        </view>
        <view class="scroll-item_info" v-if="pendingConversationAmount" @click="navigateToPendingConversation">
          <view class="item-info-top">
            <text class="item-info-top_name">待接入用户</text>
          </view>
          <view class="item-info-bottom">
            <view class="item-info-bottom-item">
              <view class="item-info-top_content">{{pendingConversationAmount}}个会话等待接入</view>
            </view>
          </view>
        </view>
        <view class="scroll-item_info" v-else @click="showNoPendingConversations">
          <view class="item-info-top">
            <text class="item-info-top_name">待接入用户</text>
          </view>
          <view class="item-info-bottom">
            <view class="item-info-bottom-item">
              <view class="item-info-top_content">暂无待接入用户</view>
            </view>
          </view>
        </view>
      </view>
      <view v-if="conversations.length!=0">
        <view class="scroll-item" v-for="(item,index) in conversations" :key="index" @click="chat(item)">
          <view class="item-head">
            <image :src="item.data.avatar" class="head-icon"></image>
            <view v-if="item.unread" class="item-head_unread">{{item.unread}}</view>
          </view>
          <view class="scroll-item_info">
            <view class="item-info-top">
              <text class="item-info-top_name">{{item.data.name}}</text>
              <view class="item-info-top_time">{{item.lastMessage.date}}</view>
            </view>
            <view class="item-info-bottom">
              <view class="item-info-bottom-item">
                <view class="item-info-top_content">
                  <view v-if="item.lastMessage.type == 'text'">
                    {{item.lastMessage.payload.text}}
                  </view>
                  <view v-else-if="item.lastMessage.type == 'video'">[视频消息]</view>
                  <view v-else-if="item.lastMessage.type == 'audio'">[语音消息]</view>
                  <view v-else-if="item.lastMessage.type == 'image'">[图片消息]</view>
                  <view v-else-if="item.lastMessage.type == 'file'">[文件消息]</view>
                  <view v-else-if="item.lastMessage.type == 'order'">[自定义消息:订单]</view>
                  <view v-else-if="item.lastMessage.type === 'CS_END'">会话已结束</view>
                  <view v-else-if="item.lastMessage.type === 'CS_ACCEPT'">接入成功</view>
                  <view v-else-if="item.lastMessage.type === 'CS_TRANSFER'">
                    {{item.lastMessage.senderId === currentAgent.id ? '已转接给' +
                                        item.lastMessage.payload.transferTo.data.name : '已接入来自' +
                                        item.lastMessage.senderData.name + '的转接'}}
                  </view>
                  <view v-else>[[未识别内容]]</view>
                </view>
                <view class="item-info-bottom_action" @click.stop="showAction(item)">
                  <image class="item-info-bottom_action-image" src="/static/images/action.png">
                  </image>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="no-conversation" v-else>
        当前没有会话
      </view>
      <view class="action-container" v-if="actionPopup.visible">
        <view class="layer" @click="closeMask"></view>
        <view class="action-box">
          <view class="action-item" @click.stop="topConversation">
            {{actionPopup.conversation.top ? '取消置顶' : '置顶聊天'}}
          </view>
          <view class="action-item" @click.stop="removeConversation">删除聊天</view>
        </view>
      </view>
    </scroll-view>
    <u-tabbar v-model="current" :list="tabbarListlLawyer" :border-top="false" inactive-color="#C8C8C8"
      @change="handleTabbar" :is-back="false" />
  </view>
</template>
<script>
  import {
    formatDate,
  } from '@/utils/service-lib/utils';
  import {
    tabbarListlLawyer,
  } from '@/utils/common.js';
  import navigation from '@/components/navigation.vue'
  export default {
    components: {
      navigation
    },
    data() {
      return {
        group_id: null,
        current: 0,
        tabbarListlLawyer,
        csteam: null,
        currentAgent: null,
        shop: null,
        unreadAmount: 0,
        pendingConversationAmount: 0,
        pendingConversations: [],
        conversations: [],
        actionPopup: {
          visible: false,
          conversation: null
        },
      };
    },
    onLoad(data) {
      this.group_id = uni.getStorageSync('group_id');
    },
    onShow() {
      let team = uni.getStorageSync('team');
      this.shop = {
        avatar: team.avatar,
        id: team.id,
        name: team.name
      };
      this.csteam = this.goEasy.im.csteam(this.shop.id);
      console.log("为哪个团队上线", this.csteam);
      if (this.goEasy.getConnectionStatus() === 'disconnected' || this.goEasy.getConnectionStatus() ===
        'connect_failed') {
        this.connectGoEasy(); //连接goeasy
      }
      this.listenConversationUpdate(); //监听会话列表变化
      this.loadConversations(); //加载会话列表
    },
    onHide() {
      // 销毁conversation监听器
      this.goEasy.im.off(this.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, this.renderLatestConversations);
      this.goEasy.im.off(this.GoEasy.IM_EVENT.PENDING_CONVERSATIONS_UPDATED, this.renderPendingConversations);
    },
    methods: {
      handleTabbar(index) {
        let url = ['/pages/conversations/conversations', '/pages/my/my']
        uni.reLaunch({
          url: url[index]
        })
      },
      connectGoEasy() {
        let userinfo = uni.getStorageSync('userinfo');
        console.log('建立连接的客服', userinfo);
        this.goEasy.connect({
          id: userinfo.id,
          data: {
            name: userinfo.nickname,
            avatar: userinfo.avatar,
            id: userinfo.id
          },
          onFailed: function(error) { //连接失败
            console.log("Failed to connect GoEasy, code:" + error.code + ",error:" + error
              .content);
          },
          onProgress: function(attempts) { //连接或自动重连中
            console.log("GoEasy is connecting", attempts);
          }
        });
      },
      // 加载最新的会话列表
      loadConversations() {
        this.goEasy.im.latestConversations({
          onSuccess: (result) => {
            console.log("获取最新的会话列表", result.content);
            this.renderLatestConversations(result.content);
          },
          onFailed: (error) => {
            // console.log('获取最新会话列表失败, error:', error);
          }
        });
        this.goEasy.im.pendingConversations({
          onSuccess: (result) => {
            this.renderPendingConversations(result.content);
          },
          onFailed: (error) => {
            // console.log('获取待接入列表失败, code:' + error.code + 'content:' + error.content);
          },
        });
      },
      listenConversationUpdate() {
        console.log("监听会话列表变化");
        // 监听会话列表变化
        this.goEasy.im.on(this.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, this.renderLatestConversations);
        this.goEasy.im.on(this.GoEasy.IM_EVENT.PENDING_CONVERSATIONS_UPDATED, this.renderPendingConversations);
      },
      renderLatestConversations(content) {
        let conversations = content.conversations;
        conversations && conversations.map((item) => {
          // 格式化时间格式
          item.lastMessage.date = formatDate(item.lastMessage.timestamp)
        });
        this.conversations = conversations;
        console.log("会话列表", this.conversations);
        this.unreadAmount = content.unreadTotal;
        this.refreshUnreadAmount();
      },
      renderPendingConversations(content) {
        this.pendingConversationAmount = content.conversations.length;
        this.refreshUnreadAmount();
      },
      refreshUnreadAmount() {
        let unreadTotal = this.unreadAmount + this.pendingConversationAmount;
        if (unreadTotal > 0) {
          uni.setTabBarBadge({
            index: 0,
            text: unreadTotal.toString()
          });
        } else {
          // uni.hideTabBarRedDot({
          // 	index: 0
          // });
        }
      },
      setPendingConversationAmount(content) {
        this.pendingConversationAmount = content.conversations.length;
      },
      topConversation() {
        let conversation = this.actionPopup.conversation;
        let description = conversation.top ? '取消置顶' : '置顶';
        uni.showLoading({
          title: '加载中...',
          mask: true
        });
        this.goEasy.im.topConversation({
          top: !conversation.top,
          conversation: conversation,
          onSuccess: function() {
            uni.hideLoading();
            console.log(description, '成功');
          },
          onFailed: function(error) {
            uni.hideLoading();
            console.log(description, '失败：', error);
          },
        });
        this.closeMask();
      },
      removeConversation() {
        this.closeMask();
        if (!this.actionPopup.conversation.ended) {
          uni.showToast({
            title: "删除失败：会话尚未结束",
            icon: 'none', //图标，支持"success"、"loading"
            duration: 2000, //提示的延迟时间，单位毫秒，默认：1500
            mask: false, //是否显示透明蒙层，防止触摸穿透，默认：false
          });
          return
        }
        uni.showModal({
          content: '确定要删除这条会话吗？',
          success: (res) => {
            if (res.confirm) {
              uni.showLoading({
                title: '加载中...',
                mask: true
              });
              let conversation = this.actionPopup.conversation;
              this.goEasy.im.removeConversation({
                conversation: conversation,
                onSuccess: function() {
                  uni.hideLoading();
                  console.log('删除会话成功');
                },
                onFailed: function(error) {
                  uni.hideLoading();
                  uni.showToast({
                    title: '删除失败',
                    duration: 3000,
                    icon: 'none'
                  });
                },
              });
            }
          }
        })
      },
      chat(item) {
        const customer = {
          id: item.id + '',
          name: item.data.name,
          avatar: item.data.avatar,
        }
        uni.navigateTo({
          url: '/pages/serviceChat/serviceChat?to=' + JSON.stringify(customer) + '&group_id=' + this
            .group_id
        });
      },
      navigateToPendingConversation() {
        uni.navigateTo({
          url: '/pages/pendingConversations/pendingConversations'
        });
      },
      showAction(item) {
        let conversation;
        this.conversations.forEach((conversationItem) => {
          if (conversationItem.id === item.id) {
            conversation = conversationItem;
          }
        })
        this.actionPopup.conversation = conversation;
        this.actionPopup.visible = true
      },
      showNoPendingConversations() {
        uni.hideLoading();
        uni.showToast({
          title: '暂无待接入用户',
          duration: 2000,
          icon: 'none'
        });
      },
      closeMask() {
        // 关闭弹窗
        this.actionPopup.visible = false
      },
    },
  }
</script>
<style scoped>
  .conversations-container {
    padding-top: 170rpx;
    width: 100%;
    overflow: hidden;
    height: 100%;
  }

  .agent-info {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-left: 30rpx;
    border-bottom: 2rpx solid #cccccc;
    padding-bottom: 20rpx;
    font-size: 30rpx;
  }

  .online-option {
    width: 80rpx;
    padding: 6rpx;
    margin-left: 10rpx;
    border-radius: 10rpx;
    text-align: center;
    font-size: 30rpx;
    border: 1px solid #cccccc;
  }

  .conversations {
    width: 750rpx;
    height: 100%;
    overflow-x: hidden;
    display: flex;
    flex-direction: column;
    overflow-x: hidden;
  }

  .conversations .scroll-item {
    height: 152rpx;
    padding-left: 32rpx;
    display: flex;
    align-items: center;
  }

  .conversations .scroll-item .head-icon {
    width: 100rpx;
    height: 100rpx;
    margin-right: 28rpx;
  }

  .conversations .scroll-item_info {
    height: 151rpx;
    width: 590rpx;
    padding-right: 32rpx;
    box-sizing: border-box;
    border-bottom: 1px solid #EFEFEF;
  }

  .conversations .scroll-item_info .item-info-top {
    padding-top: 20rpx;
    height: 60rpx;
    line-height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

  }

  .conversations .item-info-top_name {
    font-size: 34rpx;
    color: #262628;
  }

  .conversations .item-info-top_time {
    font-size: 26rpx;
    color: rgba(179, 179, 179, 0.8);
    font-family: Source Han Sans CN;
  }

  .conversations .item-info-bottom {
    height: 40rpx;
    line-height: 40rpx;
    overflow: hidden;
  }

  .conversations .item-info-bottom-item {
    display: flex;
    justify-content: space-between;
  }

  .item-info-bottom .item-info-top_content {
    font-size: 30rpx;
    color: #b3b3b3;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: flex;
  }

  .item-info-bottom .item-info-bottom_action {
    width: 50rpx;
    height: 50rpx;
    font-size: 20rpx;
  }

  .item-info-bottom_action-image {
    width: 100%;
    height: 100%;
  }

  .unread-text {
    color: #618DFF;
  }

  .item-info-bottom .item-info-bottom_unread {
    padding: 6rpx;
    background-color: #EE593C;
    color: #FFFFFF;
    font-size: 24rpx;
    line-height: 28rpx;
    border-radius: 24rpx;
    min-width: 24rpx;
    min-height: 24rpx;
    text-align: center;
  }

  .no-conversation {
    width: 100%;
    text-align: center;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 28rpx;
    color: #9D9D9D;
  }

  .item-info-bottom .item-info-bottom_action {
    width: 30rpx;
    height: 30rpx;
    font-size: 20rpx;
    background-size: 28rpx 30rpx;
  }

  .item-head {
    position: relative;
  }

  .item-head .item-head_unread {
    padding: 6rpx;
    background-color: #EE593C;
    color: #FFFFFF;
    font-size: 24rpx;
    line-height: 28rpx;
    border-radius: 24rpx;
    min-width: 24rpx;
    min-height: 24rpx;
    text-align: center;
    position: absolute;
    top: 0;
    right: 15rpx;
  }

  .action-container {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .action-container .layer {
    position: fixed;
    top: 0;
    left: 0;
    background: rgba(51, 51, 51, 0.5);
    width: 100%;
    height: 100%;
    z-index: 99;
  }

  .action-box {
    width: 400rpx;
    height: 240rpx;
    background: #ffffff;
    position: relative;
    z-index: 100;
    border-radius: 20rpx;
    overflow: hidden;
  }

  .action-item {
    text-align: center;
    line-height: 120rpx;
    font-size: 34rpx;
    color: #262628;
    border-bottom: 1px solid #EFEFEF;

  }
</style>